package com.htjc.integral.exchange.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.htjc.integral.common.enums.JdReturn;
import com.htjc.integral.common.util.UUIDGenerator;
import com.htjc.integral.common.util.UUIDUtil;
import com.htjc.integral.exchange.mapper.BpBuyRedPacketForVipMapper;
import com.htjc.integral.exchange.mapper.EcBpMemberDetailMapper;
import com.htjc.integral.exchange.mapper.EcBpMemberdetailExpandMapper;
import com.htjc.integral.exchange.mapper.EcJdCoinsExchangeInfoMapper;
import com.htjc.integral.exchange.mapper.EcJdCoinsRequestFlowMapper;
import com.htjc.integral.exchange.mapper.EcPartnerExtVipMapper;
import com.htjc.integral.exchange.service.IEcIntegralDetailService;
import com.htjc.integral.exchange.service.JdgbExchangeIntegralService;
import com.htjc.integral.exchange.utils.HttpClientUtils;
import com.htjc.integral.exchange.utils.JsonUtil;
import com.htjc.integral.model.exchange.EcBpMemberDetail;
import com.htjc.integral.model.exchange.EcBpMemberNew;
import com.htjc.integral.model.exchange.EcBpMemberdetailExpand;
import com.htjc.integral.model.exchange.EcPartner;
import com.htjc.integral.model.exchange.bo.EcJdCoinsExchangeInfo;
import com.htjc.integral.model.exchange.bo.EcJdCoinsRequestFlow;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

/**
 * 积分兑换京东钢镚的业务处理实现类
 * 
 * @author zhangjiajia
 *
 */
@Slf4j(topic = "exchangeLogger")
@Service("jdgbExchangeIntegralServiceImpl")
public class JdgbExchangeIntegralServiceImpl implements JdgbExchangeIntegralService {

	@Autowired
	private IEcIntegralDetailService ecIntegralDetailServiceImpl;

	@Autowired
	private EcBpMemberDetailMapper ecBpMemberDetailMapper;

	@Autowired
	private EcJdCoinsRequestFlowMapper coinsRequestFlowMapper;

	@Autowired
	private EcJdCoinsExchangeInfoMapper exchangeInfoMapper;

	@Autowired
	private EcBpMemberdetailExpandMapper ecBpMemberdetailExpandMapper;

	@Autowired
	private EcPartnerExtVipMapper ecPartnerMapper;

	@Autowired
	private BpBuyRedPacketForVipMapper bpBuyRedPacketForVipMapper;

//	@Autowired
//	private IAccountManagerService accountManagerService;
	
	@Value("${spring.url.QueryIntegral}")
	private String urlQueryIntegral;
	
	@Value("${spring.url.QueryStaleIntegral}")
	private String urlQueryStaleIntegral;
	
	@Value("${spring.url.DeductionIntegral}")
	private String urlDeductionIntegral;
	
	@Value("${spring.url.AddIntegral}")
	private String urlAddIntegral;

/*	*//**
	 * 积分查询接口
	 * 
	 * @throws UnsupportedEncodingException
	 *//*
	@Override
	public String queryIntegral(String uid, String clientId, String timestamp, String sign, String description)
			throws Exception {
		initializeParams();
		String memberId = uid;
		JSONObject resultMap = new JSONObject();
		String str = CLIENTID + "#" + memberId + "_" + KEY + "#" + timestamp;
		log.info("京东调用查询积分接口开始，=========================用户ID为：" + memberId);
		log.info("京东调用查询积分接口开始，参数列表：uid=" + memberId + ",clientId=" + clientId + ",timestamp=" + timestamp + ",sign="
				+ sign);

		if (memberId == null) {
			log.info("用户标识 UID不存在，用户ID为：" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg()).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				e.printStackTrace();
				log.info("系统异常--解密失败：" + memberId);
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}
		}

		if (sign != null && sign.equals(toMD5(str))) {
			try {
				int integeal = ecIntegralDetailServiceImpl.getAvailabelIntegralById(memberId);
				int integralMonth = ecIntegralDetailServiceImpl.getOverdueIntegral(memberId);
				resultMap.put("balance", integeal);
				resultMap.put("overduecredits", integralMonth);
				resultMap.put("status", true);
				resultMap.put("code", "000000");
				resultMap.put("expiryHours", "3年");
				log.info(
						"京东调用查询积分接口成功，========用户ID为：" + memberId + "当前积分为：" + integeal + "一个月内要到期的积分：" + integralMonth);
				return resultMap.toString();
			} catch (Exception e) {
				log.info("查询用户积分出现异常，用户ID为：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}
		} else {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的sign：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg()).toString();
		}
	}*/

	/**
	 * 积分查询接口
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public String queryIntegral(String uid, String clientId, String timestamp, String sign, String description)
			throws Exception {
		initializeParams();
		String memberId = uid;
		JSONObject resultMap = new JSONObject();
		String str = CLIENTID + "#" + memberId + "_" + KEY + "#" + timestamp;
		log.info("京东调用查询积分接口开始，=========================用户ID为：" + memberId);
		log.info("京东调用查询积分接口开始，参数列表：uid=" + memberId + ",clientId=" + clientId + ",timestamp=" + timestamp + ",sign="
				+ sign);

		if (memberId == null) {
			log.info("用户标识 UID不存在，用户ID为：" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg()).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				e.printStackTrace();
				log.info("系统异常--解密失败：" + memberId);
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}
		}
		
		
		log.info("=============================新接口入参准备开始======================================");
		String integralBody ="";
		String staleBody = "";
		
		/*EcPartner ecPartner = new EcPartner();
		ecPartner = accountManagerService.getUserInfos(memberId);*/
		
		// 通过memberId获取mobile作为新接口ACCOUNT_NAME
		long ecPartnerTime = System.currentTimeMillis();
		EcPartner ecPartner = ecPartnerMapper.selectPartnerByPartnerId(memberId);
		log.info("通过memberId查询EcPartner用时："+(System.currentTimeMillis()-ecPartnerTime));
		
		// 整理入参
		String ACCOUNT_NAME = ecPartner.getMobile();
		String ACCOUNT_ID = memberId;
		String BUSINESS_ID = UUIDUtil.getUUID();
		String CHANNEL_NO = "1"; // 渠道码 1 电e宝
		
		Map<String, Object> queryIntegralMap = new HashMap<String,Object>();
		queryIntegralMap.put("ACCOUNT_NAME", ACCOUNT_NAME);
		queryIntegralMap.put("ACCOUNT_ID", ACCOUNT_ID);
		queryIntegralMap.put("BUSINESS_ID", BUSINESS_ID);
		queryIntegralMap.put("CHANNEL_NO", CHANNEL_NO);
		log.info("新系统查询余额接口入参queryIntegralMap"+queryIntegralMap.toString());
		
		Map<String, Object> queryStaleIntegralMap = new HashMap<String,Object>();
		queryStaleIntegralMap.put("ACCOUNT_ID", ACCOUNT_ID);
		queryStaleIntegralMap.put("BUSINESS_ID", BUSINESS_ID);
		queryStaleIntegralMap.put("CHANNEL_NO", CHANNEL_NO);
		log.info("新系统过期积分查询接口入参queryStaleIntegralMap"+queryStaleIntegralMap.toString());
		
		// 将入参map转化为json格式的字符串
		integralBody = JsonUtil.map2json(queryIntegralMap);
		staleBody = JsonUtil.map2json(queryStaleIntegralMap);
		log.info("将新接口入参map集合转化成字符串："+integralBody+","+staleBody);
		
		if (sign != null && sign.equals(toMD5(str))) {
			try {
				int integeal = 0;
				int integralMonth = 0;
				// 调用老接口
				if (!NEW_OLD_JF_FLAG.equals(null) && "00".equals(NEW_OLD_JF_FLAG)) {
					integeal = ecIntegralDetailServiceImpl.getAvailabelIntegralById(memberId);
					integralMonth = ecIntegralDetailServiceImpl.getOverdueIntegral(memberId);
				// 调用新接口
				} else if (!NEW_OLD_JF_FLAG.equals(null) && "01".equals(NEW_OLD_JF_FLAG)) {
					long queryIntegralTimeStart = System.currentTimeMillis();
					String resultQuery = HttpClientUtils.post(urlQueryIntegral, integralBody, "application/json", "UTF-8", 50000, 50000);
					log.info("调用积分余额新接口返回查询信息："+resultQuery+"==========调用新接口用时："+(System.currentTimeMillis()-queryIntegralTimeStart));
					
					long queryQueryStaleIntegralTime = System.currentTimeMillis();
					String resultStale = HttpClientUtils.post(urlQueryStaleIntegral, staleBody, "application/json", "UTF-8", 50000, 50000);
					log.info("调用新接口过期积分返回查询信息："+resultStale+"==========调用新接口用时："+(System.currentTimeMillis()-queryQueryStaleIntegralTime));
					
					// 从返回值中取出可用余额和过期积分
					com.alibaba.fastjson.JSONObject integralResult = com.alibaba.fastjson.JSONObject.parseObject(resultQuery);
					String contentIntegral = integralResult.getString("content") == null?"":integralResult.getString("content");
					com.alibaba.fastjson.JSONObject integralContent = com.alibaba.fastjson.JSONObject.parseObject(contentIntegral);
					String BALANCE = integralContent.getString("BALANCE") == null?"":integralContent.getString("BALANCE");
					integeal = Integer.parseInt(BALANCE);
					log.info("integeal余额："+integeal);
					
					com.alibaba.fastjson.JSONObject staleResult = com.alibaba.fastjson.JSONObject.parseObject(resultStale);
					String contentStr = staleResult.getString("content") == null?"":staleResult.getString("content");
					com.alibaba.fastjson.JSONObject staleContent = com.alibaba.fastjson.JSONObject.parseObject(contentStr);
					String overduecredits = staleContent.getString("STALE_INTEGRAL") == null?"":staleContent.getString("STALE_INTEGRAL");
					integralMonth = Integer.parseInt(overduecredits);
					log.info("integralMonth过期积分："+integralMonth);
					
				}
				resultMap.put("balance", integeal);
				resultMap.put("overduecredits", integralMonth);
				resultMap.put("status", true);
				resultMap.put("code", "000000");
				resultMap.put("expiryHours", "3年");
				log.info("京东调用查询积分接口成功，========用户ID为：" + memberId + "当前积分为：" + integeal + "一个月内要到期的积分：" + integralMonth);
				return resultMap.toString();
			} catch (Exception e) {
				log.info("查询用户积分出现异常，用户ID为：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}
		} else {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的sign：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg()).toString();
		}
	}
	
	
	/**
	 * 积分扣减接口
	 * 
	 * @throws Exception
	 */
	public String deductionIntegral(String uid, String credits, String clientId, String timestamp, String description,
			String rtmOrderNum, String pointType, String sign) throws Exception {
		long startTime = System.currentTimeMillis();
		// 初始化全局变量
		initializeParams();
		long initTime = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================初始化全局变量耗时：{}", initTime - startTime);
		String memberId = uid;
		int totalNum = 0;
		if (credits != null) {// 传入参数扣减积分为空的校验===============================================================
			totalNum = new BigDecimal(credits).intValue();
			if (totalNum == 0) {
				return createReturnObject(false, "JD_9996", "扣减积分为0").toString();
			}
		} else {
			return createReturnObject(false, "JD_9996", "传入的参数扣减积分值为空").toString();
		}

		long time1 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================传入的参数扣减积分值校验耗时：{}", time1 - startTime);

		String str = CLIENTID + "#" + memberId + "_" + rtmOrderNum + "_" + totalNum + "#" + KEY + "#" + timestamp;
		String orderNum = "";

		log.info("京东调用扣减积分接口开始，参数列表：uid=" + memberId + ",credits=" + totalNum + ",clientId=" + clientId + ",timestamp="
				+ timestamp + ",sign=" + sign + ",description=" + description + ",pointType=" + pointType
				+ ",rtmOrderNum=" + rtmOrderNum);

		if (memberId == null) {
			log.info("用户id为空,menberId:" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg(), orderNum).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				log.info("系统异常--解密失败：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
			}
		}

		long time2 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================用户id校验耗时：{}", time2 - time1);
		if (rtmOrderNum == null || "".equals(rtmOrderNum)) {
			log.info("积分兑换订单编号不存在,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
			return createReturnObject(JdReturn.ORDERNUM_NOT_EXIST.isStatus(), JdReturn.ORDERNUM_NOT_EXIST.getCode(),
					JdReturn.ORDERNUM_NOT_EXIST.getMsg(), orderNum).toString();
		}
		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg(), orderNum).toString();
		}
		if (totalNum % INTEGRAL_VALUE != 0) {
			log.info("扣减的积分值不是规定值的整数倍,menberId:" + memberId + ";扣减积分为 totalNum=" + totalNum);
			return createReturnObject(JdReturn.INTEGRAL_NOT_INTEGER.isStatus(), JdReturn.INTEGRAL_NOT_INTEGER.getCode(),
					JdReturn.INTEGRAL_NOT_INTEGER.getMsg(), orderNum).toString();
		}

		long time3 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================签名参数校验耗时：{}", time3 - time2);

		Map<String, Object> checkMap = checkCoinsExchangeLimit(memberId, totalNum);
		if ((boolean) checkMap.get("flag")) {
			log.info("用户兑换量超过规定限额,menberId:" + memberId + ";" + checkCoinsExchangeLimit(memberId, totalNum).get("msg"));
			return createReturnObject(false, (String) checkMap.get("code"), (String) checkMap.get("msg"), orderNum)
					.toString();
		}

		long time4 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法===============================用户兑换数量校验耗时：{}", time4 - time3);

		// 返回信息
		log.info("调用积分扣减方法主要传参为：" + "  totalNum:" + totalNum + "  memberId:" + memberId + "  rtmOrderNum:"
				+ rtmOrderNum);
		long checkTime = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================参数校验耗时：{}", checkTime - initTime);
		try {
			// 扣减积分
			log.info("进入扣减积分开始++++++++++++++++++++++++++++++++++++++++++++===");
			Integer totalValue;
			if (totalNum < 0) {
				totalValue = totalNum * (-1);// 需要扣减的积分数
			} else {
				totalValue = totalNum;
			}
			// 先查询积分余额.这个sql查询很慢，在下面进行了优化。
			/*
			 * Map<String, Integer> integralMap =
			 * ecIntegralDetailServiceImpl.getEveryIntegralById(memberId); if
			 * (integralMap.get("availabelValue") < totalValue) {
			 * log.info("商城积分兑换京东钢镚，积分余额不足! memberId=" + memberId +
			 * " rtmOrderNum=" + rtmOrderNum); return
			 * createReturnObject(JdReturn.INTEGRAL_SHORTAGE.isStatus(),
			 * JdReturn.INTEGRAL_SHORTAGE.getCode(),
			 * JdReturn.INTEGRAL_SHORTAGE.getMsg(), orderNum).toString(); } long
			 * getEveryIntegralByIdTime = System.currentTimeMillis(); log.info(
			 * "积分扣减的业务层方法================================数据库查询积分余额耗时：{}",
			 * getEveryIntegralByIdTime-checkTime);
			 */
			// 校验用户积分数值
			Integer userTotalValue = 0;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Map<String, String> map = new HashMap<String, String>();
			map.put("bpIsFrozen", "0");
			map.put("bpChangeType", "0");
			map.put("currentTime", sdf.format(new Date()));
			map.put("bpValueRemain", "0");
			map.put("memberId", memberId);
			// 从数据库查询积分变更
			List<EcBpMemberDetail> memberDetailList = ecBpMemberDetailMapper.getMemberDetail(map);
			long getMemberDetailTime = System.currentTimeMillis();
			log.info("积分扣减的业务层方法================================从数据库查询积分变更耗时：{}", getMemberDetailTime - checkTime);
			log.info("查询到的积分明细对象列表" + memberDetailList.toString() + ",列表数量：" + memberDetailList.size());
			for (EcBpMemberDetail ecBpMemberDetail : memberDetailList) {
				userTotalValue += ecBpMemberDetail.getBpValueRemain();
			}
			// 通过计算，算出用户现有积分
			log.info("现在积分用户：" + memberId + " 积分为：" + userTotalValue);
			if (memberDetailList.size() <= 0 || totalValue > userTotalValue) {
				log.info("商城积分兑换京东钢镚，积分余额不足! memberId=" + memberId + " rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.INTEGRAL_SHORTAGE.isStatus(), JdReturn.INTEGRAL_SHORTAGE.getCode(),
						JdReturn.INTEGRAL_SHORTAGE.getMsg(), orderNum).toString();
			}

			// 查询订单有没有出现过
			List<EcJdCoinsRequestFlow> jdCoinsRequestList = coinsRequestFlowMapper.selectInfoByRtmOrderNum(rtmOrderNum);
			long selectInfoByRtmOrderNumTime = System.currentTimeMillis();
			log.info("积分扣减的业务层方法================================从数据库查询订单耗时：{}",
					selectInfoByRtmOrderNumTime - getMemberDetailTime);

			if (jdCoinsRequestList.size() <= 0) {
				// 京东钢镚兑换请求信息
				orderNum = UUIDGenerator.getInstance().getReplaceUUIDTo32();// 请求序号
				// 将请求信息插入（EC_JD_COINS_REQUEST_FLOW）京东钢镚请求记录表
				insertEcJdCoinsRequestFlow(orderNum, memberId, rtmOrderNum, description, totalNum,
						Integer.parseInt(pointType));
				long insertEcJdCoinsRequestFlowTime = System.currentTimeMillis();
				log.info("积分扣减的业务层方法================================将请求信息插入耗时：{}",
						insertEcJdCoinsRequestFlowTime - selectInfoByRtmOrderNumTime);
				log.info("商城积分兑换京东钢镚，将请求信息存入京东钢镚请求记录表，memberId=" + memberId + " rtmOrderNum=" + rtmOrderNum);
			} else {
				log.info("商城积分兑换京东钢镚，查询京东钢镚请求记录表，已存在该订单号对应的订单； rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.ORDERNUM_ALREADY_EXIST.isStatus(),
						JdReturn.ORDERNUM_ALREADY_EXIST.getCode(), JdReturn.ORDERNUM_ALREADY_EXIST.getMsg(), orderNum)
								.toString();
			}
			long forbeforeTime = System.currentTimeMillis();
			for (EcBpMemberDetail ecBpMemberDetail : memberDetailList) {
				if (ecBpMemberDetail.getBpValueRemain() >= totalValue && totalValue > 0) {
					EcBpMemberDetail ecBpMemberDetail2 = new EcBpMemberDetail();
					// 更新增加积分信息的剩余积分
					Map<String, Object> updateMap = new HashMap<String, Object>();
					updateMap.put("detailId", ecBpMemberDetail.getDetailId());
					updateMap.put("totalValue", totalValue * (-1));
					updateMap.put("version", ecBpMemberDetail.getVersion());
					log.info("===================更新增加积分信息的剩余积分1开始，参数为：{}", updateMap.toString());// 更新增加积分信息的剩余积分开始
					Integer upback = ecBpMemberDetailMapper.updateMemberDetailById(updateMap);
					log.info("===================更新增加积分信息的剩余积分1结束");
					if (upback <= 0) {
						throw new RuntimeException("更新增加积分信息的剩余积分1出现异常，请稍后重试！");
					}
					// 插入扣减积分信息
					String detailId = UUIDUtil.getUUID();
					ecBpMemberDetail2.setDetailId(detailId);
					ecBpMemberDetail2.setMemberId(memberId);
					ecBpMemberDetail2.setBpValue(totalValue * (-1));
					ecBpMemberDetail2.setCreateTime(new Date());
					ecBpMemberDetail2.setOriginId(orderNum);
					ecBpMemberDetail2.setOriginRemark("商城积分兑换京东钢镚");
					ecBpMemberDetail2.setMerchantId(null);
					ecBpMemberDetail2.setBpYear(ecBpMemberDetail.getBpYear());// 记录关联生成的年份
					ecBpMemberDetail2.setBizcodeIdCreate(ecBpMemberDetail.getBizcodeIdCreate());
					ecBpMemberDetail2.setChannelIdCreate(ecBpMemberDetail.getChannelIdCreate());
					ecBpMemberDetail2.setBizcodeIdConsume("ESGCC_JDGB");
					ecBpMemberDetail2.setChannelIdConsume("JD_GANGBENG");
					ecBpMemberDetail2.setUseDetailId(ecBpMemberDetail.getDetailId());// 存储使用的是那条信息的积分
					ecBpMemberDetail2.setBpChangeType("1");// 积分扣减
					// ecBpMemberDetail2.setPowerUserNo("");
					// ecBpMemberDetail2.setProvinceId("");
					log.info("===================插将积分扣减信息存进积分变更信息表开始，参数为：{}", ecBpMemberDetail2.toString());
					ecBpMemberDetailMapper.insertMemberDetail(ecBpMemberDetail2);// 将积分扣减信息存进积分变更信息表
					log.info("===================插将积分扣减信息存进积分变更信息表结束");

					log.info("===================插入积分流水明细详情表开始,参数rtmOrderNum={}", ecBpMemberDetail2.toString());
					// 插入积分流水明细详情表
					insertEcBpMemberdetailExpand(ecBpMemberDetail2, rtmOrderNum);
					log.info("===================插入积分流水明细详情表结束");
					break;
				} else {
					EcBpMemberDetail ecBpMemberDetail2 = new EcBpMemberDetail();
					// 更新增加积分信息的剩余积分
					// Integer remainValue = 0;
					Map<String, Object> updateMap = new HashMap<String, Object>();
					updateMap.put("detailId", ecBpMemberDetail.getDetailId());
					updateMap.put("totalValue", totalValue * (-1));
					updateMap.put("version", ecBpMemberDetail.getVersion());
					log.info("===================更新增加积分信息的剩余积分2开始,参数为：{}", updateMap.toString());
					Integer upback = ecBpMemberDetailMapper.updateMemberDetailById(updateMap);
					log.info("===================更新增加积分信息的剩余积分2结束");
					if (upback <= 0) {
						throw new RuntimeException("更新增加积分信息的剩余积分2出现异常，请稍后重试！");
					}
					// 插入扣减积分信息
					String detailId = (UUID.randomUUID().toString()).replaceAll("-", "");
					ecBpMemberDetail2.setDetailId(detailId);
					ecBpMemberDetail2.setMemberId(memberId);
					ecBpMemberDetail2.setBpValue(ecBpMemberDetail.getBpValueRemain() * (-1));
					ecBpMemberDetail2.setCreateTime(new Date());
					ecBpMemberDetail2.setOriginId(orderNum);
					ecBpMemberDetail2.setOriginRemark("商城积分兑换京东钢镚");
					ecBpMemberDetail2.setMerchantId(null);
					ecBpMemberDetail2.setBpYear(ecBpMemberDetail.getBpYear());// 记录关联生成的年份
					ecBpMemberDetail2.setBizcodeIdCreate(ecBpMemberDetail.getBizcodeIdCreate());
					ecBpMemberDetail2.setChannelIdCreate(ecBpMemberDetail.getChannelIdCreate());
					ecBpMemberDetail2.setBizcodeIdConsume("ESGCC_JDGB");
					ecBpMemberDetail2.setChannelIdConsume("JD_GANGBENG");
					ecBpMemberDetail2.setUseDetailId(ecBpMemberDetail.getDetailId());// 存储使用的是那条信息的积分
					ecBpMemberDetail2.setBpChangeType("1");// 积分扣减
					// ecBpMemberDetail2.setPowerUserNo("");
					// ecBpMemberDetail2.setProvinceId("");
					log.info("===================将积分扣减信息存进积分变更信息表开始,参数为：{}", ecBpMemberDetail2.toString());
					ecBpMemberDetailMapper.insertMemberDetail(ecBpMemberDetail2);// 将积分扣减信息存进积分变更信息表
					log.info("===================将积分扣减信息存进积分变更信息表结束");

					log.info("===================插入积分流水明细详情表开始,参数rtmOrderNum={}", rtmOrderNum);
					// 插入积分流水明细详情表
					insertEcBpMemberdetailExpand(ecBpMemberDetail2, rtmOrderNum);
					log.info("===================插入积分流水明细详情表结束");
					totalValue -= ecBpMemberDetail.getBpValueRemain();
				}
			}
			long forTime = System.currentTimeMillis();
			log.info("积分扣减的业务层方法================================for循环耗时：{}", forTime - forbeforeTime);

			// 变更用户总积分
			List<EcBpMemberNew> ecBpMemberNewList = ecBpMemberDetailMapper.getBpValueById(memberId);
			log.info("=================变更用户总积分" + ecBpMemberNewList);
			Map<String, Object> memberNewMap = new HashMap<String, Object>();
			memberNewMap.put("memberId", memberId);
			memberNewMap.put("bpValue", totalNum);
			memberNewMap.put("version", ecBpMemberNewList.get(0).getVersion());

			log.info("===================变更用户总积分开始,参数为:{}", memberNewMap.toString());
			Integer upback = ecBpMemberDetailMapper.updateMemberNewById(memberNewMap);
			log.info("===================变更用户总积分结束");
			if (upback <= 0) {
				throw new RuntimeException("变更用户总积分出现异常，请稍后重试！");
			}
			log.info("===================将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表开始,参数orderNum={}", orderNum);
			// 将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表
			insertEcJdCoinsExchangeInfo(orderNum, rtmOrderNum, totalNum, memberId, description, "积分扣减成功");
			log.info("===================将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表结束");
			log.info("===================更新订单状态开始,参数orderNum={}", orderNum);
			// 更新订单状态
			modifyOrderStatus(orderNum, "2");
			log.info("===================更新订单状态结束");
			long updateTime = System.currentTimeMillis();
			log.info("积分扣减的业务层方法================================更新订单状态耗时：{}", updateTime - forTime);

			return createReturnObject(true, JdReturn.MINUS_INTEGRAL_SUCCESS.getCode(),
					JdReturn.MINUS_INTEGRAL_SUCCESS.getMsg(), orderNum).toString();// 返回码待确定
		} catch (Exception e) {
			log.info("=================扣减积分出现异常，用户ID为memberId={}， RTM订单号为rtmOrderNum={}，错误信息={}", memberId, rtmOrderNum,e);
//			e.printStackTrace();
			return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
					JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
		}
	}

	
	
	/**
	 * 积分扣减接口
	 * 
	 * @throws Exception
	 */
	public String deductionIntegralNew(String uid, String credits, String clientId, String timestamp, String description,
			String rtmOrderNum, String pointType, String sign) throws Exception {
		long startTime = System.currentTimeMillis();
		String phone = "";//获取手机号
		// 初始化全局变量
		initializeParams();
		long initTime = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================初始化全局变量耗时：{}", initTime - startTime);
		String memberId = uid;
		int totalNum = 0;
		if (credits != null) {// 传入参数扣减积分为空的校验===============================================================
			totalNum = new BigDecimal(credits).intValue();
			if (totalNum == 0) {
				return createReturnObject(false, "JD_9996", "扣减积分为0").toString();
			}
		} else {
			return createReturnObject(false, "JD_9996", "传入的参数扣减积分值为空").toString();
		}

		long time1 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================传入的参数扣减积分值校验耗时：{}", time1 - startTime);

		String str = CLIENTID + "#" + memberId + "_" + rtmOrderNum + "_" + totalNum + "#" + KEY + "#" + timestamp;
		String orderNum = "";

		log.info("京东调用扣减积分接口开始，参数列表：uid=" + memberId + ",credits=" + totalNum + ",clientId=" + clientId + ",timestamp="
				+ timestamp + ",sign=" + sign + ",description=" + description + ",pointType=" + pointType
				+ ",rtmOrderNum=" + rtmOrderNum);
		if (memberId == null) {
			log.info("用户id为空,menberId:" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg(), orderNum).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				log.info("系统异常--解密失败：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
			}
		}

		long time2 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================用户id校验耗时：{}", time2 - time1);
		if (rtmOrderNum == null || "".equals(rtmOrderNum)) {
			log.info("积分兑换订单编号不存在,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
			return createReturnObject(JdReturn.ORDERNUM_NOT_EXIST.isStatus(), JdReturn.ORDERNUM_NOT_EXIST.getCode(),
					JdReturn.ORDERNUM_NOT_EXIST.getMsg(), orderNum).toString();
		}
		//49da936ce410a5c27dc06952fc5c732a //12bbe35fee67238296b32b5b40e96ae0
		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg(), orderNum).toString();
		}
		if (totalNum % INTEGRAL_VALUE != 0) {
			log.info("扣减的积分值不是规定值的整数倍,menberId:" + memberId + ";扣减积分为 totalNum=" + totalNum);
			return createReturnObject(JdReturn.INTEGRAL_NOT_INTEGER.isStatus(), JdReturn.INTEGRAL_NOT_INTEGER.getCode(),
					JdReturn.INTEGRAL_NOT_INTEGER.getMsg(), orderNum).toString();
		}

		long time3 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================签名参数校验耗时：{}", time3 - time2);

		Map<String, Object> checkMap = checkCoinsExchangeLimit(memberId, totalNum);
		//这个限制可能有问题
		if ((boolean) checkMap.get("flag")) {
			log.info("用户兑换量超过规定限额,menberId:" + memberId + ";" + checkCoinsExchangeLimit(memberId, totalNum).get("msg"));
			return createReturnObject(false, (String) checkMap.get("code"), (String) checkMap.get("msg"), orderNum)
					.toString();
		}

		long time4 = System.currentTimeMillis();
		log.info("积分扣减的业务层方法===============================用户兑换数量校验耗时：{}", time4 - time3);

		// 返回信息
		log.info("调用积分扣减方法主要传参为：" + "  totalNum:" + totalNum + "  memberId:" + memberId + "  rtmOrderNum:"
				+ rtmOrderNum);
		long checkTime = System.currentTimeMillis();
		log.info("积分扣减的业务层方法================================参数校验耗时：{}", checkTime - initTime);
		try {
			// 扣减积分
			log.info("进入扣减积分开始++++++++++++++++++++++++++++++++++++++++++++===");
			
			// 获取手机号作为ACCOUNT_NAME
			/*EcPartner ecPartner = new EcPartner();
			ecPartner = accountManagerService.getUserInfos(memberId);*/
			
			long ecPartnerTime = System.currentTimeMillis();
			EcPartner ecPartner = ecPartnerMapper.selectPartnerByPartnerId(memberId);
			if(ecPartner!=null){
				//获取手机号码对象不为空
				phone = ecPartner.getMobile();
				log.info("手机号："+ecPartner.getMobile());
				log.info("通过memberId查询EcPartner用时："+(System.currentTimeMillis()-ecPartnerTime));
	
			}else{
				//获取手机号码对象为空 直接返回
				return createReturnObject(JdReturn.keyError.isStatus(), JdReturn.keyError.getCode(),
						JdReturn.keyError.getMsg(), orderNum).toString();
			}
			
			Integer totalValue;
			if (totalNum < 0) {
				totalValue = totalNum * (-1);// 需要扣减的积分数
			} else {
				totalValue = totalNum;
			}
			//查询积分余额
			String integral = _QueryIntegral(phone,memberId);
			//判断用户积分是否足够扣减
			int syIntegral = 0;
			if(integral!=null&&!"".equals(integral)){
				
				syIntegral = new BigDecimal(integral).intValue();
				if(syIntegral<totalValue){
					//积分余额不足
					log.info("商城积分兑换京东钢镚，积分余额不足! memberId=" + memberId +"rtmOrderNum"+rtmOrderNum+ " 扣减积分=" + totalValue);
					return createReturnObject(JdReturn.INTEGRAL_SHORTAGE.isStatus(), JdReturn.INTEGRAL_SHORTAGE.getCode(),
							JdReturn.INTEGRAL_SHORTAGE.getMsg(), orderNum).toString();
				}
			}else{
				//积分余额查询为空 直接return 
				
				log.info("商城积分兑换京东钢镚，积分查询为空! memberId=" + memberId +"rtmOrderNum"+rtmOrderNum+ " 扣减积分=" + totalValue);
				return createReturnObject(JdReturn.INTEGRAL_SHORTAGE.isStatus(), JdReturn.INTEGRAL_SHORTAGE.getCode(),
						JdReturn.INTEGRAL_SHORTAGE.getMsg(), orderNum).toString();
				
			}

			// 查询订单有没有出现过
			List<EcJdCoinsRequestFlow> jdCoinsRequestList = coinsRequestFlowMapper.selectInfoByRtmOrderNum(rtmOrderNum);
			long selectInfoByRtmOrderNumTime = System.currentTimeMillis();

			if (jdCoinsRequestList.size() <= 0) {
				// 京东钢镚兑换请求信息
				orderNum = UUIDGenerator.getInstance().getReplaceUUIDTo32();// 请求序号
				// 将请求信息插入（EC_JD_COINS_REQUEST_FLOW）京东钢镚请求记录表
				insertEcJdCoinsRequestFlow(orderNum, memberId, rtmOrderNum, description, totalNum,
						Integer.parseInt(pointType));
				long insertEcJdCoinsRequestFlowTime = System.currentTimeMillis();
				log.info("积分扣减的业务层方法================================将请求信息插入耗时：{}",
						insertEcJdCoinsRequestFlowTime - selectInfoByRtmOrderNumTime);
				log.info("商城积分兑换京东钢镚，将请求信息存入京东钢镚请求记录表，memberId=" + memberId + " rtmOrderNum=" + rtmOrderNum);
			} else {
				log.info("商城积分兑换京东钢镚，查询京东钢镚请求记录表，已存在该订单号对应的订单； rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.ORDERNUM_ALREADY_EXIST.isStatus(),
						JdReturn.ORDERNUM_ALREADY_EXIST.getCode(), JdReturn.ORDERNUM_ALREADY_EXIST.getMsg(), orderNum)
								.toString();
			}
			//扣减积分
			boolean _DedIntegral = _DedIntegral(phone, memberId, totalValue+"");
			if(!_DedIntegral){
				return createReturnObject(true, JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();// 返回码待确定
			}

			log.info("===================将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表开始,参数orderNum={}", orderNum);
			// 将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表
			insertEcJdCoinsExchangeInfo(orderNum, rtmOrderNum, totalNum, memberId, description, "积分扣减成功");
			log.info("===================将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表结束");
			log.info("===================更新订单状态开始,参数orderNum={}", orderNum);
			// 更新订单状态
			modifyOrderStatus(orderNum, "2");
			log.info("===================更新订单状态结束");
			return createReturnObject(true, JdReturn.MINUS_INTEGRAL_SUCCESS.getCode(),
					JdReturn.MINUS_INTEGRAL_SUCCESS.getMsg(), orderNum).toString();// 返回码待确定
		} catch (Exception e) {
			log.info("=================扣减积分出现异常，用户ID为memberId={}， RTM订单号为rtmOrderNum={}，错误信息={}", memberId, rtmOrderNum,e);
			return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
					JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
		}
	}
	
	
	
	/**
	 * 积分退回接口
	 * 
	 * @throws Exception
	 */
	public String backIntegralNew(String uid, String credits, String clientId, String timestamp, String description,
			String rtmOrderNum, String pointType, String sign) throws Exception {
		log.info("进入退回积分开始++++++++++++++++++++++++++++++++++++++++++++===");
		String phone = "";
		initializeParams();
		String memberId = uid;
		int totalNum = 0;

		if (credits != null) {// 传入参数扣减积分为空的校验===============================================================
			totalNum = new BigDecimal(credits).intValue();
		} else {
			return createReturnObject(false, "JD_9996", "传入的参数扣减积分值为空").toString();
		}

		String str = CLIENTID + "#" + memberId + "_" + rtmOrderNum + "_" + totalNum + "#" + KEY + "#" + timestamp;
		String orderNum = "";
		log.info("京东调用积分退回接口开始，参数列表：uid=" + memberId + ",credits=" + totalNum + ",clientId=" + clientId + ",timestamp="
				+ timestamp + ",sign=" + sign + ",description=" + description + ",pointType=" + pointType
				+ ",rtmOrderNum=" + rtmOrderNum);

		// 解码用户编号
		if (memberId == null) {
			log.info("用户id为空,menberId:" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg(), orderNum).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				log.info("系统异常--解密失败：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
			}
		}
		if (rtmOrderNum == null || "".equals(rtmOrderNum)) {
			log.info("积分兑换订单编号不存在,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
			return createReturnObject(JdReturn.ORDERNUM_NOT_EXIST.isStatus(), JdReturn.ORDERNUM_NOT_EXIST.getCode(),
					JdReturn.ORDERNUM_NOT_EXIST.getMsg(), orderNum).toString();
		}
		//签名校验
		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg(), orderNum).toString();
		}

		try {
			Integer totalValue;
			if (totalNum < 0) {
				totalValue = totalNum * (-1);// 需要扣减的积分数
			} else {
				totalValue = totalNum;
			}
			// 退回积分 获取手机号作为ACCOUNT_NAME
			/*EcPartner ecPartner = new EcPartner();
			long ecPartnerTime = System.currentTimeMillis();
			ecPartner = accountManagerService.getUserInfos(memberId);*/
			
			long ecPartnerTime = System.currentTimeMillis();
			EcPartner ecPartner = ecPartnerMapper.selectPartnerByPartnerId(memberId);
			if(ecPartner!=null){
				//获取手机号码对象不为空
				phone = ecPartner.getMobile();
				log.info("手机号："+ecPartner.getMobile());
				log.info("通过memberId查询EcPartner用时："+(System.currentTimeMillis()-ecPartnerTime));
	
			}else{
				//获取手机号码对象为空 直接返回
				return createReturnObject(JdReturn.keyError.isStatus(), JdReturn.keyError.getCode(),
						JdReturn.keyError.getMsg(), orderNum).toString();
			}
			
			String integral = _QueryIntegral(phone, memberId);
			int syIntegral = 0;
			if(integral!=null){
				syIntegral = new BigDecimal(integral).intValue();
				if(syIntegral<totalValue){
					//积分余额不足
					log.info("当前用户没有可返回的积分,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
					return createReturnObject(JdReturn.NO_INTEGRAL_RETURN.isStatus(), JdReturn.NO_INTEGRAL_RETURN.getCode(),
							"当前用户没有可返回的积分,rtmOrderNum:" + rtmOrderNum, orderNum).toString();// 返回码待确定
				}
				
			}else{
				log.info("当前用户没有可返回的积分,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
				return createReturnObject(JdReturn.NO_INTEGRAL_RETURN.isStatus(), JdReturn.NO_INTEGRAL_RETURN.getCode(),
						"当前用户没有可返回的积分,rtmOrderNum:" + rtmOrderNum, orderNum).toString();// 返回码待确定
			}

			// 查询订单有没有出现过
			List<EcJdCoinsRequestFlow> jdCoinsRequestList = selectEcJdCoinsRequestFlowInfo(rtmOrderNum, "3");
			if (jdCoinsRequestList.size() == 0) {
				orderNum = UUIDUtil.getUUID();
				insertEcJdCoinsRequestFlow(orderNum, memberId, rtmOrderNum, description, totalValue,
						Integer.parseInt(pointType));
				log.info("商城积分兑换京东钢镚，将请求信息存入京东钢镚请求记录表，memberId=" + memberId + " rtmOrderNum=" + rtmOrderNum);
			} else {
				log.info("商城积分兑换京东钢镚，查询京东钢镚请求记录表，已存在该订单号对应的订单； rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.ORDERNUM_ALREADY_EXIST.isStatus(),
						JdReturn.ORDERNUM_ALREADY_EXIST.getCode(), JdReturn.ORDERNUM_ALREADY_EXIST.getMsg(), orderNum)
								.toString();
			}

			//新增积分
			boolean _AddIntegral = _AddIntegral(phone, memberId, totalValue+"");
			if(!_AddIntegral){
				log.info("京东钢镚退回积分，增加积分失败； rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
			}
			
			// 将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表
			insertEcJdCoinsExchangeInfo(orderNum, rtmOrderNum, totalValue, memberId, description, "积分退回成功");
			// 更新订单状态
			modifyOrderStatus(orderNum, "3");
			// 退换积分成功以后，需要将之前扣减积分的订单状态改为：4--表示积分已退回
			modifyOrderStatus("4", rtmOrderNum, "2");

			return createReturnObject(JdReturn.ORDER_REFUND_SUCCESS.isStatus(), JdReturn.ORDER_REFUND_SUCCESS.getCode(),
					JdReturn.ORDER_REFUND_SUCCESS.getMsg(), orderNum).toString();
		} catch (Exception e) {
			log.info("=================退回积分出现异常，用户ID为：" + memberId);
			e.printStackTrace();
			return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
					JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
		}
	}
	
	
	
	
	
	/**
	 * 积分退回接口
	 * 
	 * @throws Exception
	 */
	public String backIntegral(String uid, String credits, String clientId, String timestamp, String description,
			String rtmOrderNum, String pointType, String sign) throws Exception {
		log.info("进入退回积分开始++++++++++++++++++++++++++++++++++++++++++++===");
		initializeParams();
		String memberId = uid;
		int totalNum = 0;

		if (credits != null) {// 传入参数扣减积分为空的校验===============================================================
			totalNum = new BigDecimal(credits).intValue();
		} else {
			return createReturnObject(false, "JD_9996", "传入的参数扣减积分值为空").toString();
		}

		int totalValue = 0;
		String str = CLIENTID + "#" + memberId + "_" + rtmOrderNum + "_" + totalNum + "#" + KEY + "#" + timestamp;
		String orderNum = "";
		log.info("京东调用积分退回接口开始，参数列表：uid=" + memberId + ",credits=" + totalNum + ",clientId=" + clientId + ",timestamp="
				+ timestamp + ",sign=" + sign + ",description=" + description + ",pointType=" + pointType
				+ ",rtmOrderNum=" + rtmOrderNum);

		// 解码用户编号
		if (memberId == null) {
			log.info("用户id为空,menberId:" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg(), orderNum).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				log.info("系统异常--解密失败：" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
			}
		}
		if (rtmOrderNum == null || "".equals(rtmOrderNum)) {
			log.info("积分兑换订单编号不存在,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
			return createReturnObject(JdReturn.ORDERNUM_NOT_EXIST.isStatus(), JdReturn.ORDERNUM_NOT_EXIST.getCode(),
					JdReturn.ORDERNUM_NOT_EXIST.getMsg(), orderNum).toString();
		}
		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg(), orderNum).toString();
		}

		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("memberId", memberId);
			map.put("rtmOrderNum", rtmOrderNum);
			List<EcBpMemberDetail> memberDetailList = ecBpMemberDetailMapper.getMemberDetail(map);
			if (memberDetailList.size() <= 0) {
				log.info("当前用户没有可返回的积分,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum);
				return createReturnObject(JdReturn.NO_INTEGRAL_RETURN.isStatus(), JdReturn.NO_INTEGRAL_RETURN.getCode(),
						"当前用户没有可返回的积分,rtmOrderNum:" + rtmOrderNum, orderNum).toString();// 返回码待确定
			}

			// 查询订单有没有出现过
			List<EcJdCoinsRequestFlow> jdCoinsRequestList = selectEcJdCoinsRequestFlowInfo(rtmOrderNum, "3");
			if (jdCoinsRequestList.size() == 0) {
				// 将请求信息插入（EC_JD_COINS_REQUEST_FLOW）京东钢镚请求记录表
				// orderNum = UUIDGenerator.getInstance().getReplaceUUIDTo32();
				orderNum = UUIDUtil.getUUID();
				insertEcJdCoinsRequestFlow(orderNum, memberId, rtmOrderNum, description, totalNum,
						Integer.parseInt(pointType));
				log.info("商城积分兑换京东钢镚，将请求信息存入京东钢镚请求记录表，memberId=" + memberId + " rtmOrderNum=" + rtmOrderNum);
			} else {
				log.info("商城积分兑换京东钢镚，查询京东钢镚请求记录表，已存在该订单号对应的订单； rtmOrderNum=" + rtmOrderNum);
				return createReturnObject(JdReturn.ORDERNUM_ALREADY_EXIST.isStatus(),
						JdReturn.ORDERNUM_ALREADY_EXIST.getCode(), JdReturn.ORDERNUM_ALREADY_EXIST.getMsg(), orderNum)
								.toString();
			}

			// 判断传入的积分参数是否与订单扣减时的积分值一致
			for (EcBpMemberDetail ecBpMemberDetail : memberDetailList) {
				totalValue += -ecBpMemberDetail.getBpValue();
			}
			if (totalValue != totalNum) {
				log.info("传入的积分值与订单扣减时传入的积分值不一致,menberId:" + memberId + ",rtmOrderNum:" + rtmOrderNum + ";传入的积分值为："
						+ totalNum + ",订单扣减的积分值为：" + totalValue);
				return createReturnObject(JdReturn.INTEGRAL_INCONFORMITY.isStatus(),
						JdReturn.INTEGRAL_INCONFORMITY.getCode(), "传入的积分值与订单扣减时传入的积分值不一致,rtmOrderNum:" + rtmOrderNum,
						orderNum).toString();
			}

			log.info(
					"进入原路返还积分++++++++++++++++++++++++++++++++++++++++++++原路返还积分开始;memberDetailList" + memberDetailList);
			for (EcBpMemberDetail ecBpMemberDetail : memberDetailList) {
				// 原路返还积分
				Map<String, Object> updateMap = new HashMap<String, Object>();
				Integer bpValueChange = ecBpMemberDetail.getBpValue();
				updateMap.put("detailId", ecBpMemberDetail.getUseDetailId());
				updateMap.put("totalValue", bpValueChange * (-1));
				Integer upback = ecBpMemberDetailMapper.updateMemberDetailById(updateMap);
				log.info("进入返还积分++++++++++++++++++++++++++++++++++++++++++++upback=" + upback + "detailId"
						+ ecBpMemberDetail.getUseDetailId());
				log.info("detailId=" + ecBpMemberDetail.getUseDetailId() + "totalValue=" + bpValueChange * (-1));
				if (upback <= 0) {
					throw new RuntimeException("请稍后重试！");
				}
				// 插入变更信息
				EcBpMemberDetail ecBpMemberDetail2 = new EcBpMemberDetail();
				String detailId = (UUID.randomUUID().toString()).replaceAll("-", "");
				ecBpMemberDetail2.setDetailId(detailId);
				ecBpMemberDetail2.setMemberId(memberId);
				ecBpMemberDetail2.setBpValue(bpValueChange * (-1));
				ecBpMemberDetail2.setCreateTime(new Date());
				ecBpMemberDetail2.setOriginId(orderNum);
				ecBpMemberDetail2.setOriginRemark("兑换京东钢镚返还积分");
				ecBpMemberDetail2.setBpYear(ecBpMemberDetail.getBpYear());// 记录关联生成的年份
				ecBpMemberDetail2.setBizcodeIdCreate(ecBpMemberDetail.getBizcodeIdCreate());
				ecBpMemberDetail2.setChannelIdCreate(ecBpMemberDetail.getChannelIdCreate());
				ecBpMemberDetail2.setBizcodeIdConsume("ESGCC_JDGB");
				ecBpMemberDetail2.setChannelIdConsume("JD_GANGBENG");
				ecBpMemberDetail2.setUseDetailId(ecBpMemberDetail.getUseDetailId());// 存储使用的是那条信息的积分
				ecBpMemberDetail2.setBpChangeType("0");// 积分返还
				ecBpMemberDetail2.setBpIsFrozen("0");
				ecBpMemberDetail2.setBpValueRemain(0);
				ecBpMemberDetail2.setStartTime(ecBpMemberDetail.getStartTime());
				ecBpMemberDetail2.setEndTime(ecBpMemberDetail.getEndTime());
				// ecBpMemberDetail2.setPowerUserNo("");
				// ecBpMemberDetail2.setProvinceId("");
				ecBpMemberDetailMapper.insertMemberDetail(ecBpMemberDetail2);// 将积分扣减信息存进积分变更信息表
				// 插入积分流水明细详情表
				insertEcBpMemberdetailExpand(ecBpMemberDetail2, rtmOrderNum);

				log.info("进入原路返还积分结束++++++++++++++++++++++++++++++++++++++++++++插入变更信息" + ecBpMemberDetail2);
			}
			// 变更用户总积分
			List<EcBpMemberNew> ecBpMemberNewList = ecBpMemberDetailMapper.getBpValueById(memberId);
			Map<String, Object> memberNewMap = new HashMap<String, Object>();
			memberNewMap.put("memberId", memberId);
			memberNewMap.put("bpValue", totalNum);
			memberNewMap.put("version", ecBpMemberNewList.get(0).getVersion());
			log.info("进入返还积分++++++++++++++++++++++++++++++++++++++++++++变更用户总积分" + memberNewMap);
			Integer upback = ecBpMemberDetailMapper.updateMemberNewById(memberNewMap);
			if (upback <= 0) {
				throw new RuntimeException("更新用户总积分出现异常！");
			}
			// 将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表
			insertEcJdCoinsExchangeInfo(orderNum, rtmOrderNum, totalNum, memberId, description, "积分退回成功");
			// 更新订单状态
			modifyOrderStatus(orderNum, "3");

			// 退换积分成功以后，需要将之前扣减积分的订单状态改为：4--表示积分已退回
			modifyOrderStatus("4", rtmOrderNum, "2");

			return createReturnObject(JdReturn.ORDER_REFUND_SUCCESS.isStatus(), JdReturn.ORDER_REFUND_SUCCESS.getCode(),
					JdReturn.ORDER_REFUND_SUCCESS.getMsg(), orderNum).toString();
		} catch (Exception e) {
			log.info("=================退回积分出现异常，用户ID为：" + memberId);
			e.printStackTrace();
			return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
					JdReturn.SYSTEM_ERR.getMsg(), orderNum).toString();
		}
	}
	
	
	
	

	/**
	 * 增加积分接口
	 * 
	 * @throws Exception
	 */
	// @SuppressWarnings("static-access")
	public String addIntegral(String uid, String credits, String clientId, String timestamp, String description,
			String rtmOrderNum, String pointType, String sign) throws Exception {
		log.info("京东钢镚兑换商城积分，增加积分+++++++++++++++++++++++++===");
		initializeParams();
		String memberId = uid;
		int totalNum = new BigDecimal(credits).intValue();
		// String str =
		// CLIENTID+"#"+memberId+"_"+rtmOrderNum+"_"+totalNum+"#"+KEY+"#"+timestamp;
		String orderNum = UUIDUtil.getUUID();
		// Calendar calendar = Calendar.getInstance();
		log.info("京东调用增加积分接口开始，参数列表：uid=" + memberId + ",credits=" + totalNum + ",clientId=" + clientId + ",timestamp="
				+ timestamp + ",sign=" + sign + ",description=" + description + ",pointType=" + pointType
				+ ",rtmOrderNum=" + rtmOrderNum);

		return createReturnObject(true, JdReturn.PAUSE_BUSINESS_SUCCESS.getCode(),
				JdReturn.PAUSE_BUSINESS_SUCCESS.getMsg(), orderNum).toString();

		// /* 1.入参校验 */
		// if(memberId == null){
		// log.info("用户id为空,menberId:"+memberId);
		// return createReturnObject(false,"JD_9997",encodeChineseStr("用户标识 UID
		// 不存在"),null).toString();
		// }else{
		// try {
		// memberId = getFromBase64(memberId);
		// log.info("用户标识 UID解密为："+memberId);
		// } catch (Exception e) {
		// log.info("系统异常--解密失败："+memberId);
		// e.printStackTrace();
		// return
		// createReturnObject(false,"JD_9999",encodeChineseStr("系统异常"),null).toString();
		// }
		// }
		// if(rtmOrderNum == null || "".equals(rtmOrderNum)){
		// log.info("积分兑换订单编号不存在,menberId:"+memberId+",rtmOrderNum:"+rtmOrderNum);
		// return
		// createReturnObject(false,"JD_9996",encodeChineseStr("积分兑换订单编号不存在"),null).toString();
		// }
		// if(sign==null || !sign.equals(toMD5(str))){
		// log.info("签名参数与本地生成签名不匹配,menberId:"+memberId+",sign:"+sign+",生成的签名："+toMD5(str));
		// return
		// createReturnObject(false,"JD_9998",encodeChineseStr("签名校验错误"),null).toString();
		// }
		//
		// try {
		// //查询订单有没有出现过
		// List<EcJdCoinsRequestFlow> jdCoinsRequestList =
		// coinsRequestFlowMapper.selectInfoByRtmOrderNum(rtmOrderNum);
		// if(jdCoinsRequestList.size() == 0){
		// /* 2.保存请求信息 */
		// //将请求信息插入（EC_JD_COINS_REQUEST_FLOW）京东钢镚请求记录表
		// insertEcJdCoinsRequestFlow(orderNum,memberId,rtmOrderNum,description,totalNum,Integer.parseInt(pointType));
		// log.info("商城积分兑换京东钢镚，将请求信息存入京东钢镚请求记录表，memberId="+memberId+"
		// rtmOrderNum=" +rtmOrderNum);
		// }else{
		// log.info("商城积分兑换京东钢镚，查询京东钢镚请求记录表，已存在该订单号对应的订单； rtmOrderNum="
		// +rtmOrderNum);
		// return
		// createReturnObject(false,"JD_9801",encodeChineseStr("订单已存在，请确认订单号是否正确!"),orderNum).toString();
		// }
		//
		// /*
		// * 3.根据[交易号]和[平台ID]查询【积分转换请求记录】,判断此交易号是否处理过,处理过就返回处理过的数据,否则进行积分转换处理
		// */
		// Map<String, Object> pars = new HashMap<String, Object>();
		// pars.put("dealId", rtmOrderNum);
		// pars.put("platformId", clientId);
		//// EcIntegralexchangeRecord eRecord =
		// ecIntegralExchangeRecordMapper.selectByDealId(pars);
		//// if (eRecord != null) {
		//// log.info("=======此增加积分的订单已经处理，处理状态：【" + eRecord.getResponseCode() +
		// eRecord.getResponseDesc()+"】rtm订单号为："+rtmOrderNum);
		//// if("0000".equals(eRecord.getResponseCode())){
		//// return
		// createReturnObject(true,"000000",encodeChineseStr("京东钢镚兑换商城积分成功"),orderNum).toString();
		//// }else{
		//// return
		// createReturnObject(false,"JD_9999",encodeChineseStr("系统异常"),orderNum).toString();
		//// }
		//// }
		// /* 4.根据用户id和年份查询是否存在【积分信息】,如果存在则增加积分,否则新增一条【积分信息】 */
		// // 积分新的处理逻辑
		// int currentYear = calendar.get(Calendar.YEAR);
		// Map<String, String>useTimeMap = new HashMap<String, String>();
		// useTimeMap.put("bizcodeIdCreate", "JDGB_ESGCC");
		// useTimeMap.put("channelIdCreate", "JD_GANGBENG");
		// List<EcBpUseTime> useTimeList =
		// ecBpMemberDetailMapper.getUseTimeById(useTimeMap);
		// int makeUse = 0;
		// int keepUse = 365*3;
		// if(useTimeList.size()>0){
		// EcBpUseTime ecBpUseTime = useTimeList.get(0);
		// log.info("获取有效使用："+ecBpUseTime.toString());
		// makeUse = (ecBpUseTime.getMakeUse()
		// !=null)?ecBpUseTime.getMakeUse():0;
		// keepUse = (ecBpUseTime.getKeepUse()
		// !=null)?ecBpUseTime.getKeepUse():(365*3);
		// }
		// EcBpMemberDetail ecBpMemberDetail = new EcBpMemberDetail();
		// String detailId = (UUID.randomUUID().toString()).replace("-", "");
		// ecBpMemberDetail.setDetailId(detailId);
		// ecBpMemberDetail.setMemberId(memberId);
		// ecBpMemberDetail.setCreateTime(new Date());
		// ecBpMemberDetail.setBpValue(totalNum);
		// ecBpMemberDetail.setOriginId(orderNum);
		// ecBpMemberDetail.setOriginRemark("京东钢镚兑换商城积分");
		// ecBpMemberDetail.setMerchantId(null);
		// ecBpMemberDetail.setBpYear(currentYear);//增加积分存储当前年份
		// ecBpMemberDetail.setScaleTrans(null);
		// ecBpMemberDetail.setBpTransition(null);
		// ecBpMemberDetail.setBoundId(null);
		// ecBpMemberDetail.setAccIsNo(null);
		// ecBpMemberDetail.setBpValueRemain(totalNum);
		// ecBpMemberDetail.setBizcodeIdCreate("JDGB_ESGCC");
		// ecBpMemberDetail.setChannelIdCreate("JD_GANGBENG");
		// calendar.add(calendar.DATE, makeUse);
		// ecBpMemberDetail.setStartTime(calendar.getTime());
		// calendar.add(Calendar.DATE, keepUse);
		// ecBpMemberDetail.setEndTime(calendar.getTime());
		// ecBpMemberDetail.setBpIsFrozen("0");//积分未冻结
		// ecBpMemberDetail.setBizcodeIdConsume(null);
		// ecBpMemberDetail.setChannelIdConsume(null);
		// ecBpMemberDetail.setUseDetailId(null);
		// ecBpMemberDetail.setBpChangeType("0");//积分增加
		// ecBpMemberDetailMapper.insertMemberDetail(ecBpMemberDetail);
		//
		// //插入积分流水明细详情表
		// insertEcBpMemberdetailExpand(ecBpMemberDetail, rtmOrderNum);
		//
		// //变更用户总积分表
		// List<EcBpMemberNew> ecBpMemberNewList =
		// ecBpMemberDetailMapper.getBpValueById(memberId);
		// if(ecBpMemberNewList == null || ecBpMemberNewList.size() <=0 ){
		// //插入
		// Map<String, Object>memberNewMap = new HashMap<String, Object>();
		// memberNewMap.put("memberId", memberId);
		// memberNewMap.put("bpValue", totalNum);
		// ecBpMemberDetailMapper.insertMemberNew(memberNewMap);
		// }else{
		// //更新
		// Map<String, Object>memberNewMap = new HashMap<String, Object>();
		// memberNewMap.put("memberId", memberId);
		// memberNewMap.put("bpValue", totalNum);
		// memberNewMap.put("version", ecBpMemberNewList.get(0).getVersion());
		// Integer upback =
		// ecBpMemberDetailMapper.updateMemberNewById(memberNewMap);
		// if(upback <= 0){
		// throw new RuntimeException("请稍后再试！");
		// }
		// }
		//
		// //在增加积分时，需要将数据插入到【积分转换请求记录表】（这是之前的逻辑），但是感觉现在的逻辑不用记录到这个表中，后面有待检验--这个逻辑如果出现异常的话也需要插入对应信息，代码见下面第二段
		// insertEcIntegralexchangeRecord(rtmOrderNum,memberId,clientId,totalNum,Integer.toString(totalNum),"0000","请求成功","1");
		// //将兑换信息插入到（EC_JD_COINS_EXCHANGE_INFO）京东钢镚兑换信息表
		// insertEcJdCoinsExchangeInfo(orderNum,rtmOrderNum,totalNum,memberId,description,"京东钢镚兑换商城积分成功");
		// //更新订单状态
		// modifyOrderStatus(orderNum,"1");
		// return
		// createReturnObject(true,"000000",encodeChineseStr("京东钢镚兑换商城积分成功"),orderNum).toString();//返回码待确定

		// } catch (Exception e) {
		// insertEcIntegralexchangeRecord(rtmOrderNum,memberId,clientId,totalNum,"0","0007","接口异常","2");
		// log.info("=================增加积分出现异常，用户ID为："+memberId);
		// e.printStackTrace();
		// return
		// createReturnObject(false,"JD_9999",encodeChineseStr("系统异常"),orderNum).toString();
		// }
	}

	/**
	 * 订单状态查询接口
	 * 
	 * @throws Exception
	 */
	public String queryOrderStatus(String clientId, String timestamp, String rtmOrderNum, String sign)
			throws Exception {
		log.info("京东钢镚兑换商城积分，订单状态查询接口+++++++++++++++++++++++++===");
		initializeParams();
		String str = CLIENTID + "#" + rtmOrderNum + "_" + KEY + "#" + timestamp;
		log.info("京东调用订单状态查询接口开始，参数列表：clientId=" + clientId + ",timestamp=" + timestamp + ",sign=" + sign
				+ ",rtmOrderNum=" + rtmOrderNum);

		/* 1.入参校验 */
		if (rtmOrderNum == null || "".equals(rtmOrderNum)) {
			log.info("积分兑换订单编号不存在,rtmOrderNum:" + rtmOrderNum);
			return createReturnObject(JdReturn.ORDERNUM_NOT_EXIST.isStatus(), JdReturn.ORDERNUM_NOT_EXIST.getCode(),
					JdReturn.ORDERNUM_NOT_EXIST.getMsg(), "").toString();
		}
		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg(), "").toString();
		}

		try {
			List<EcJdCoinsRequestFlow> jdCoinsRequestList = coinsRequestFlowMapper.selectInfoByRtmOrderNum(rtmOrderNum);
			if (jdCoinsRequestList == null || jdCoinsRequestList.size() <= 0) {
				log.info("没有查询到该订单编号对应的请求信息,订单编号为 rtmOrderNum:" + rtmOrderNum);
				return createReturnObject(JdReturn.NO_ORDER_INFORMATION.isStatus(),
						JdReturn.NO_ORDER_INFORMATION.getCode(), JdReturn.NO_ORDER_INFORMATION.getMsg(), "").toString();
				// }else if(jdCoinsRequestList.size() > 1){
				// log.info("该订单编号对应多条请求信息,订单编号为 rtmOrderNum:"+rtmOrderNum);
				// return
				// createReturnObject(false,"JD_9996",encodeChineseStr("该订单编号对应多条请求信息"),null).toString();
			} else {
				EcJdCoinsRequestFlow ecJdCoinsRequestFlow = jdCoinsRequestList.get(0);
				JSONObject resultMap = createReturnObject(JdReturn.QUERY_ORDERSTATUS_SUCCESS.isStatus(),
						JdReturn.QUERY_ORDERSTATUS_SUCCESS.getCode(), JdReturn.QUERY_ORDERSTATUS_SUCCESS.getMsg(),
						ecJdCoinsRequestFlow.getJid());
				resultMap.put("orderStatus", ecJdCoinsRequestFlow.getStatus());
				return resultMap.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("=================查询订单状态出现异常，订单编号为：" + rtmOrderNum);
			return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
					JdReturn.SYSTEM_ERR.getMsg(), "").toString();
		}
	}

	/**
	 * 用户授权登录接口
	 * 
	 * @throws Exception
	 */
	public String userAuthorizeLogin(String clientId, String timestamp, String uid, String sign) throws Exception {
		initializeParams();
		String memberId = uid;
		JSONObject resultMap = new JSONObject();
		String str = CLIENTID + "#" + memberId + "_" + KEY + "#" + timestamp;
		log.info("京东调用用户授权登录接口接口开始，参数列表：uid=" + memberId + ",clientId=" + clientId + ",timestamp=" + timestamp
				+ ",sign=" + sign);

		if (sign == null || !sign.equals(toMD5(str))) {
			log.info("签名参数与本地生成签名不匹配,menberId:" + memberId + ",sign:" + sign + ",生成的签名：" + toMD5(str));
			return createReturnObject(JdReturn.SIGN_CHECK_ERR.isStatus(), JdReturn.SIGN_CHECK_ERR.getCode(),
					JdReturn.SIGN_CHECK_ERR.getMsg()).toString();
		}

		if (memberId == null) {
			log.info("用户id为空,menberId:" + memberId);
			return createReturnObject(JdReturn.UID_NOT_EXIST.isStatus(), JdReturn.UID_NOT_EXIST.getCode(),
					JdReturn.UID_NOT_EXIST.getMsg()).toString();
		} else {
			try {
				memberId = getFromBase64(memberId);
				log.info("用户标识 UID解密为：" + memberId);
			} catch (Exception e) {
				log.info("系统异常--解密失败" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}

			try {
				EcPartner ecPartner = queryUserInfo(memberId);
				// 根据用户id查询商城是否有该用户
				if (ecPartner == null) {
					log.info("根据用户 id不能查询到用户信息,menberId:" + memberId);
					return createReturnObject(JdReturn.UID_NO_INFORMATION.isStatus(),
							JdReturn.UID_NO_INFORMATION.getCode(), JdReturn.UID_NO_INFORMATION.getMsg()).toString();
				} else {
					resultMap.put("status", true);
					resultMap.put("code", JdReturn.QUERY_SUCCESS.getCode());
					resultMap.put("msg", JdReturn.QUERY_SUCCESS.getMsg());
					resultMap.put("clientId", "42");
					resultMap.put("uid", getBase64(ecPartner.getPartnerId()));
					resultMap.put("userStatus",
							ecPartner.getMemberStatus() != null && ecPartner.getMemberStatus().equals("2") ? 1 : 0);
					log.info("根据用户 id查询用户信息成功,menberId:" + memberId);
					return resultMap.toString();
				}
			} catch (Exception e) {
				log.info("系统异常--查询账户信息异常" + memberId);
				e.printStackTrace();
				return createReturnObject(JdReturn.SYSTEM_ERR.isStatus(), JdReturn.SYSTEM_ERR.getCode(),
						JdReturn.SYSTEM_ERR.getMsg()).toString();
			}

		}
	}

	// 验证用户兑换量是否超限：日=100，月=200，年=1000
	private Map<String, Object> checkCoinsExchangeLimit(String memberId, int totalNum) {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag = false;
		int num = totalNum / INTEGRAL_VALUE;
		long time1 = System.currentTimeMillis();
		List<EcJdCoinsRequestFlow> jdCoinsRequestList = coinsRequestFlowMapper.selectCoinsExchangeLimitNum(memberId);
		log.debug("开始请求数据库时间耗时：{}", System.currentTimeMillis() - time1);
		int dInt = 0;
		int mInt = 0;
		int yInt = 0;
		String msg = "";
		String code = "";
		for (EcJdCoinsRequestFlow e : jdCoinsRequestList) {
			// 京东账户当日已经兑换的总数
			if ("1".equals(e.getName())) {
				dInt = Integer.valueOf(e.getCoinsNumber());
			}
			// 京东账户当月已经兑换的总数
			if ("2".equals(e.getName())) {
				mInt = Integer.valueOf(e.getCoinsNumber());
			}
			// 商城用户当日兑换京东钢镚的数量
			if ("3".equals(e.getName())) {
				yInt = Integer.valueOf(e.getCoinsNumber());
			}
		}

		if (num + dInt > COINS_LIMIT_NUMBER_DAY) {
			flag = JdReturn.JD_DAY_INTEGRAL.isStatus();
			code = JdReturn.JD_DAY_INTEGRAL.getCode();
			msg = "用户当日已兑换" + dInt + "个钢镚，当日还能兑换" + (COINS_LIMIT_NUMBER_DAY - dInt) + "个钢镚。 ";
		}
		if (num + mInt > COINS_LIMIT_NUMBER_MONTH) {
			flag = JdReturn.JD_MONTH_INTEGRAL.isStatus();
			code = JdReturn.JD_MONTH_INTEGRAL.getCode();
			msg = "用户当月已兑换" + mInt + "个钢镚，当月还能兑换" + (COINS_LIMIT_NUMBER_MONTH - mInt) + "个钢镚。  ";
		}
		if (num + yInt > COINS_LIMIT_NUMBER_YEAR) {
			flag = JdReturn.JD_YEAR_INTEGRAL.isStatus();
			code = JdReturn.JD_YEAR_INTEGRAL.getCode();
			msg = "用户当年已兑换" + yInt + "个钢镚，当年还能兑换" + (COINS_LIMIT_NUMBER_YEAR - yInt) + "个钢镚。";
		}
		map.put("flag", flag);
		map.put("msg", msg);
		map.put("code", code);
		return map;
	}

	// 从统一用户平台查询用户信息，根据用户ID。如果统一用户平台存在信息，商城不存在，进行用户信息同步
	private EcPartner queryUserInfo(String memberId) throws Exception {
		try {
			return ecPartnerMapper.selectPartnerByPartnerId(memberId);
		} catch (Exception e) {
			throw e;
		}
	}

	// //将返回的中文转换为utf-8的编码格式
	// private String encodeChineseStr(String str){
	// try{
	// log.info("--===============--系统默认的编码方式+++++++++++++"+Charset.defaultCharset());
	// return URLDecoder.decode(str,"UTF-8");
	// }catch(Exception e){
	// e.printStackTrace();
	// return createReturnObject(false,"JD_9999","charset
	// error",null).toString();
	// }
	// }

	// 构建返回对象
	private JSONObject createReturnObject(Boolean status, String code, String msg, String orderNum) {
		JSONObject resultMap = new JSONObject();
		resultMap.put("status", status);
		resultMap.put("code", code);
		resultMap.put("msg", msg);
		resultMap.put("orderNum", orderNum);
		return resultMap;
	}

	// 构建返回对象
	private JSONObject createReturnObject(Boolean status, String code, String msg) {
		JSONObject resultMap = new JSONObject();
		resultMap.put("status", status);
		resultMap.put("code", code);
		resultMap.put("msg", msg);
		return resultMap;
	}

	// 京东钢镚兑换商城积分时，将请求信息插入到--积分转换请求记录（EC_INTEGRALEXCHANGE_RECORD）
	// private void insertEcIntegralexchangeRecord(String rtmOrderNum,String
	// memberId,String clientId,int totalNum,String exchangePoint,
	// String responseCode,String responseDesc,String handleState){
	// EcIntegralexchangeRecord insertRecordFour = new
	// EcIntegralexchangeRecord();
	// String uuid = UUIDGenerator.getInstance().getReplaceUUID();
	// insertRecordFour.setId(uuid);
	// insertRecordFour.setDealId(rtmOrderNum);
	// insertRecordFour.setMobile(memberId);
	// insertRecordFour.setPlatformId(clientId);
	// insertRecordFour.setApplyPoint(Integer.toString(totalNum));
	// insertRecordFour.setExchangedPoint(exchangePoint);
	// insertRecordFour.setResponseCode(responseCode);
	// insertRecordFour.setResponseDesc(responseDesc);
	// insertRecordFour.setHandleState(handleState);
	// insertRecordFour.setHandleDatetime(new Date());
	// ecIntegralExchangeRecordMapper.insertSelective(insertRecordFour);
	// }

	// 京东钢镚与商城积分进行兑换时，将积分消耗信息插入到--积分流水明细详情表（EC_BP_MEMBERDETAIL_EXPAND）
	private void insertEcBpMemberdetailExpand(EcBpMemberDetail ecBpMemberDetail, String rtmOrderNum) {
		EcBpMemberdetailExpand ecBpMemberdetailExpand = new EcBpMemberdetailExpand();
		ecBpMemberdetailExpand.setId(ecBpMemberDetail.getDetailId());
		ecBpMemberdetailExpand.setOriginId(ecBpMemberDetail.getOriginId());
		ecBpMemberdetailExpand.setOriginRemark(ecBpMemberDetail.getOriginRemark());
		ecBpMemberdetailExpand.setBizcodeIdCreate(ecBpMemberDetail.getBizcodeIdCreate());
		ecBpMemberdetailExpand.setChannelIdCreate(ecBpMemberDetail.getChannelIdCreate());
		ecBpMemberdetailExpand.setBizcodeIdConsume(ecBpMemberDetail.getBizcodeIdConsume());
		ecBpMemberdetailExpand.setChannelIdConsume(ecBpMemberDetail.getChannelIdConsume());
		ecBpMemberdetailExpand.setRtmOrderNum(rtmOrderNum);
		ecBpMemberdetailExpandMapper.insertSelective(ecBpMemberdetailExpand);
	}

	// 京东钢镚与商城积分进行兑换时，将兑换信息插入到--京东钢镚兑换信息表（EC_JD_COINS_EXCHANGE_INFO）
	private void insertEcJdCoinsExchangeInfo(String did, String rtmOrderNum, int totalNum, String memberId,
			String description, String message) {
		EcJdCoinsExchangeInfo exchangeInfo = new EcJdCoinsExchangeInfo();
		exchangeInfo.setDid(did);
		exchangeInfo.setExchangememono(null);
		exchangeInfo.setExchangeNumber(Integer.toString(totalNum / INTEGRAL_VALUE));
		exchangeInfo.setExchangeTime(new Date());
		exchangeInfo.setLoginaccount(null);
		exchangeInfo.setMobile(null);
		exchangeInfo.setName(null);
		exchangeInfo.setPartnerId(memberId);
		exchangeInfo.setPin(null);
		exchangeInfo.setResponsecode("0000");
		exchangeInfo.setResponsemessage(message);
		exchangeInfo.setUseIntegral(Integer.toString(totalNum));
		exchangeInfo.setRtmOrderNum(rtmOrderNum);
		exchangeInfo.setDescription(description);
		exchangeInfoMapper.insertEcJdCoinsExchangeInfo(exchangeInfo);
	}

	// 京东钢镚与商城积分进行兑换时，将请求信息插入到--京东钢镚请求信息记录表（EC_JD_COINS_REQUEST_FLOW）
	private void insertEcJdCoinsRequestFlow(String orderNum, String memberId, String rtmOrderNum, String description,
			int totalNum, int pointType) {
		EcJdCoinsRequestFlow record = new EcJdCoinsRequestFlow();
		record.setJid(orderNum);
		record.setMemberId(memberId);
		record.setRtmOrderNum(rtmOrderNum);
		record.setDescription(description);
		record.setCoinsNumber(Integer.toString(totalNum / INTEGRAL_VALUE));
		record.setUseIntegnal(Integer.toString(totalNum));
		record.setRequestTime(new Date());
		record.setStatus("0");
		record.setPointType(Integer.toString(pointType));
		this.coinsRequestFlowMapper.insertEcJdCoinsRequestFlow(record);
	}

	// 修改订单状态--京东钢镚请求信息记录表（EC_JD_COINS_REQUEST_FLOW）
	private void modifyOrderStatus(String jid, String status) {
		EcJdCoinsRequestFlow record = new EcJdCoinsRequestFlow();
		record.setJid(jid);
		record.setStatus(status);
		this.coinsRequestFlowMapper.updateStatusByJid(record);
	}

	// 修改订单状态--京东钢镚请求信息记录表（EC_JD_COINS_REQUEST_FLOW）
	private void modifyOrderStatus(String status, String rtmOrderNum, String pointType) {
		EcJdCoinsRequestFlow record = new EcJdCoinsRequestFlow();
		record.setStatus(status);
		record.setRtmOrderNum(rtmOrderNum);
		record.setPointType(pointType);
		this.coinsRequestFlowMapper.updateStatusByJid(record);
	}

	// 修改订单状态--京东钢镚请求信息记录表（EC_JD_COINS_REQUEST_FLOW）
	private List<EcJdCoinsRequestFlow> selectEcJdCoinsRequestFlowInfo(String rtmOrderNum, String status) {
		EcJdCoinsRequestFlow record = new EcJdCoinsRequestFlow();
		record.setRtmOrderNum(rtmOrderNum);
		record.setStatus(status);
		return this.coinsRequestFlowMapper.selectInfoByObject(record);
	}

	// MD5加密
	private String toMD5(String signature) {
		MessageDigest mDigest = null;
		try {
			mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(signature.getBytes());
			return encodeHex(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			log.error("NoSuchAlgorithmException", e);
		}
		return null;
	}

	private String encodeHex(byte[] bytes) {
		StringBuffer buffer = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10)
				buffer.append("0");
			buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buffer.toString();
	}

	// 加密
	private String getBase64(String inputData) {
		try {
			if (null == inputData) {
				return null;
			}
			return new String(Base64.encodeBase64(inputData.getBytes("utf-8")), "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error(inputData, e);
		}

		return null;
	}

	// 解密
	private String getFromBase64(String inputData) {
		try {
			if (null == inputData) {
				return null;
			}
			return new String(Base64.decodeBase64(inputData.getBytes("utf-8")), "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error(inputData, e);
		}

		return null;
	}

	// 从参数配置表中查询配置参数
	public String queryParamByCode(String code) throws Exception {
		return bpBuyRedPacketForVipMapper.selectParasByCode(code);
	}
	private String NEW_OLD_JF_FLAG;
	
	private String CLIENTID;
	private String KEY;
	private int INTEGRAL_VALUE;
	private int COINS_LIMIT_NUMBER_DAY;
	private int COINS_LIMIT_NUMBER_MONTH;
	private int COINS_LIMIT_NUMBER_YEAR;

	// 初始化全局变量
	public void initializeParams() throws Exception {
		NEW_OLD_JF_FLAG = queryParamByCode("NEW_OLD_JF_FLAG");
		
		CLIENTID = queryParamByCode("integral.exchange.gangbeng.clientid");
		KEY = queryParamByCode("integral.exchange.gangbeng.key");
		INTEGRAL_VALUE = Integer.parseInt(queryParamByCode("integral.exchange.gangbeng.integral_value"));
		COINS_LIMIT_NUMBER_DAY = Integer
				.parseInt(queryParamByCode("integral.exchange.gangbeng.coins_limit_number_day"));
		COINS_LIMIT_NUMBER_MONTH = Integer
				.parseInt(queryParamByCode("integral.exchange.gangbeng.coins_limit_number_month"));
		COINS_LIMIT_NUMBER_YEAR = Integer
				.parseInt(queryParamByCode("integral.exchange.gangbeng.coins_limit_number_year"));
	}

	private String _QueryIntegral(String phone,String  accountId){
		String integral = "0";
		try{
			//查询积分余额
			Map<String, Object> queryIntegralMap = new HashMap<String,Object>();
			queryIntegralMap.put("ACCOUNT_NAME", phone);
			queryIntegralMap.put("ACCOUNT_ID", accountId);
			queryIntegralMap.put("BUSINESS_ID", UUIDUtil.getUUID());
			queryIntegralMap.put("CHANNEL_NO", "1");//这里不应该是5
			log.info("新系统查询余额接口入参queryIntegralMap"+queryIntegralMap.toString());
			String integralBody = JsonUtil.map2json(queryIntegralMap);
			log.info("新系统查询余额接口入参integralBody"+integralBody);
			String resultQuery = HttpClientUtils.post(urlQueryIntegral, integralBody, "application/json", "UTF-8", 50000, 50000);
			log.info("新系统查询余额接口返回参数resultQuery"+resultQuery);
			com.alibaba.fastjson.JSONObject integralResult = com.alibaba.fastjson.JSONObject.parseObject(resultQuery);
			String contentIntegral = integralResult.getString("content") == null?"":integralResult.getString("content");
			com.alibaba.fastjson.JSONObject integralContent = com.alibaba.fastjson.JSONObject.parseObject(contentIntegral);
			integral = integralContent.getString("BALANCE") == null?"":integralContent.getString("BALANCE");
			log.info("integeal余额："+integral);
			
		
		}catch (Exception e) {
			// TODO: handle exception
		}
	
		
		return integral;
	}

	
	private boolean _DedIntegral(String phone ,String accountId,String integral){
		boolean result  = false;
		try{
			// 积分扣减入参map集合
			Map<String, Object> deductionIntegralMap = new HashMap<String,Object>();
			deductionIntegralMap.put("ACCOUNT_NAME", phone);
			deductionIntegralMap.put("ACCOUNT_ID", accountId);
			deductionIntegralMap.put("BUSINESS_ID", UUIDUtil.getUUID());
			deductionIntegralMap.put("CHANNEL_NO", "1");//这里不应该是 5
			deductionIntegralMap.put("BUSS_TYPE", "03");
			deductionIntegralMap.put("BUSS_DISCRIBLE", "京东钢镚扣减积分"+integral);
			
			deductionIntegralMap.put("OPERATION_TYPE", "01");
			deductionIntegralMap.put("INTEGRAL", integral);
			SimpleDateFormat dtformat = new SimpleDateFormat("YYYYMMddHHmmssSSS");
			String DEAL_TIME = dtformat.format(new Date());
			SimpleDateFormat adformat = new SimpleDateFormat("YYYYMMdd");
			String ACCT_DATE = adformat.format(new Date());
			deductionIntegralMap.put("DEAL_TIME", DEAL_TIME);
			deductionIntegralMap.put("ACCT_DATE", ACCT_DATE);
			log.info("积分扣减入参map集合deductionIntegralMap"+deductionIntegralMap.toString());
			String deductionInParams = JsonUtil.map2json(deductionIntegralMap);
			log.info("将新接口入参map集合转化成字符串deductionInParams："+deductionInParams);
			long deductionIntegralTimeStart = System.currentTimeMillis();
			String resultDeduction = HttpClientUtils.post(urlDeductionIntegral, deductionInParams, "application/json", "UTF-8", 50000, 50000);
			log.info("调用扣减新接口返回查询信息："+resultDeduction+"==========调用新接口用时："+(System.currentTimeMillis()-deductionIntegralTimeStart));
			
			// 处理返回信息
			com.alibaba.fastjson.JSONObject jsonObjectResult = com.alibaba.fastjson.JSONObject.parseObject(resultDeduction);
			String rcode = jsonObjectResult.getString("rcode") == null?"":jsonObjectResult.getString("rcode");
			String message = jsonObjectResult.getString("message") == null?"":jsonObjectResult.getString("message");
			String content = jsonObjectResult.getString("content") == null?"":jsonObjectResult.getString("content");
			com.alibaba.fastjson.JSONObject jsonObjectContent = com.alibaba.fastjson.JSONObject
					.parseObject(content);
			String DESCRIBE = jsonObjectContent.getString("DESCRIBE") == null?"":jsonObjectContent.getString("DESCRIBE");
			if (rcode!=null&&"0".equals(rcode)) {
				if(jsonObjectContent!=null){
					String status = jsonObjectContent.getString("STATUS");
					if(status!=null&&"1".equals(status)){
						result  = true;
					}
				}
			}
		
		
		}catch (Exception e) {
			// TODO: handle exception
			
		}
	
		
		return result;
	}
	
	
	private boolean _AddIntegral(String phone ,String accountId ,String integral){
		boolean result = false;
		try {
			log.info("开始为新接口入参赋值......");
			String BUSINESS_ID = UUIDUtil.getUUID();
			String CHANNEL_NO = "1";
			String BUSS_TYPE = "03";
			String OPERATION_TYPE = "01";
			String BUSS_DISCRIBLE = "积分回退";
			String DEAL_TIME = new SimpleDateFormat("YYYYMMddHHmmssSSS").format(new Date());
			String CREATE_DATE = new SimpleDateFormat("YYYYMMdd").format(new Date());
			String ACCT_DATE = new SimpleDateFormat("YYYYMMdd").format(new Date());
			
			Map<String, Object> addIntegralMap = new HashMap<String,Object>();
			addIntegralMap.put("ACCOUNT_ID", accountId);
			addIntegralMap.put("ACCOUNT_NAME", phone);
			addIntegralMap.put("BUSINESS_ID", BUSINESS_ID);
			addIntegralMap.put("CHANNEL_NO", CHANNEL_NO);
			addIntegralMap.put("BUSS_TYPE", BUSS_TYPE);
			addIntegralMap.put("OPERATION_TYPE", OPERATION_TYPE);
			addIntegralMap.put("BUSS_DISCRIBLE", BUSS_DISCRIBLE);
			addIntegralMap.put("INTEGRAL", integral);
			addIntegralMap.put("DEAL_TIME", DEAL_TIME);
			addIntegralMap.put("CREATE_DATE", CREATE_DATE);
			addIntegralMap.put("ACCT_DATE", ACCT_DATE);
			log.info("将新接口入参封装成map集合："+addIntegralMap.toString());

			// 将入参map转化成HttpClientUtils工具类可传的json格式字符串
			String body = JsonUtil.map2json(addIntegralMap);
			log.info("将新接口入参map转换成字符串："+body);
			String resultStr = HttpClientUtils.post(urlAddIntegral, body, "application/json", "UTF-8", 50000, 50000);
			
			com.alibaba.fastjson.JSONObject jsonResult = com.alibaba.fastjson.JSONObject.parseObject(resultStr);
			String rcode = jsonResult.getString("rcode");
//			String message = jsonResult.getString("message");
			if(rcode!=null&&"0".equals(rcode)){
				//解析参数
				String content = jsonResult.getString("content") == null?"":jsonResult.getString("content");
				com.alibaba.fastjson.JSONObject jsonObjectContent = com.alibaba.fastjson.JSONObject
						.parseObject(content);
				
				if(jsonObjectContent!=null){
					String status = jsonObjectContent.getString("STATUS");
					if(status!=null&&"1".equals(status)){
						result  = true;
					}
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return result ;
	}
	
	
}
